package cn.jbolt.ai.core.fileSplit;

import cn.jbolt.ai.klb.entity.AiFile;
import com.jboltai.capability.message.AIMessage;
import com.jboltai.event.EventError;
import com.jboltai.event.ai.aichat.AIChatEvent;
import com.jboltai.event.handler.AIChatEventHandler;
import com.jboltai.util.other.StringUtil;
import com.jboltai.util.text.TextUtil;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AISplitHandler implements AIChatEventHandler {
    private static final Logger logger = LoggerFactory.getLogger(AISplitHandler.class);

    private static final Pattern liPattern = Pattern.compile("<li>(.*?)</li>", Pattern.DOTALL);

    private AiFile aiFile;

    public AISplitHandler(AiFile aiFile) {
        this.aiFile = aiFile;
    }

    @Override
    public void onSuccess(AIChatEvent event, AIMessage msg) {
        StringBuilder oriText = event.getAttr("oriText");
        String content = msg.getContent();//获取的分割点
        logger.info("原文：{}" , oriText);
        logger.info("分割位置：{}" , content);

        content = StringUtil.extractByRegex(content, "<ul>(.*?)</ul>");

        if (content != null) {
            //根据提取的分割字符，将原文本进行切分
            List<String> blocks = extractBlocks(oriText, content);

            event.setAttrs("blocks", blocks);
        }
    }

    private static @NotNull List<String> extractBlocks(StringBuilder oriText, String content) {
        Matcher liMatcher = liPattern.matcher(content);
        List<String> splitResult = new ArrayList<>();
        while (liMatcher.find()) {
            String splitText = liMatcher.group(1);
            if (splitText.length() > 0) {
                int index = oriText.indexOf(splitText);
                if (index == -1 && splitText.length() > 10) {
                    //第一次找不到分割点，尝试缩短
                    index = oriText.indexOf(splitText.substring(0, splitText.length() / 2));
                }
                if (index <= 0) continue; //开头的标题处就要分割的话，先不管

                String subText = oriText.substring(0, index);
                oriText.delete(0, index);
                logger.debug("分割位置文本：{}", subText);
                if (subText != null && subText.length() > 10) {
                    splitResult.add(subText);
                }
            }
        }
        return splitResult;
    }




    @Override
    public void onFail(AIChatEvent event, EventError error) {
        logger.error("AI进行语义切分时发生异常:{}", error.getFullMsg());
        FileSplitCache.addFailCount(aiFile.getId());
    }
    @Override
    public void onStart(AIChatEvent event) {
        if (FileSplitCache.hasFailed(aiFile.getId())) {
            event.cancel();
        }
    }

    @Override
    public void onComplete(AIChatEvent event) {

    }


}
